package com.example.moshudriver.activity;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.BeeFramework.Utils.ImageUtil;
import com.BeeFramework.Utils.Utils;
import com.BeeFramework.activity.BaseActivity;
import com.BeeFramework.model.BusinessResponse;
import com.BeeFramework.view.RoundedWebImageView;
import com.BeeFramework.view.ToastView;
import com.sgr.dykdriver.R;
import com.example.moshudriver.model.UserBalanceModel;
import com.example.moshudriver.model.UserModel;
import com.example.moshudriver.protocol.ApiInterface;
import com.example.moshudriver.protocol.ENUM_USER_GENDER;
import com.example.moshudriver.protocol.USER;
import com.example.moshudriver.protocol.userprofileResponse;
import com.example.moshudriver.tools.MessageConstant;
import com.example.moshudriver.tools.O2OMobile;
import com.example.moshudriver.tools.O2OMobileAppConst;
import com.example.moshudriver.tools.SESSION;
import com.external.androidquery.callback.AjaxStatus;
import com.external.eventbus.EventBus;
import com.external.maxwin.view.IXListViewListener;
import com.external.maxwin.view.XListView;
import com.nostra13.universalimageloader.core.ImageLoader;

//个人中心
public class F0_ProfileActivity extends BaseActivity implements
		BusinessResponse, View.OnClickListener, IXListViewListener {
	public static final String USER_ID = "user_id";
	private int mUserId;
	// private ImageView mBack;
	private RoundedWebImageView mAvatar;
	private TextView mName;
	private TextView mSignature;
	private TextView mBalance;
	private UserBalanceModel mUserBalance;
	private USER mUser;
	private RelativeLayout change_nickname;
	// private RelativeLayout change_avartar;
	private RelativeLayout change_gender;
	private RelativeLayout change_mobile;
	private RelativeLayout change_sinagture;
	private RelativeLayout change_brief;
	private SharedPreferences mShared;
	protected ImageLoader mImageLoader = ImageLoader.getInstance();
	private Dialog mDialog;
	// private File mFileDir;
	// private File mFile;
	private ImageView mRefresh;
	private final int REQUEST_CAMERA = 1;
	private final int REQUEST_PHOTO = 2;
	private final int REQUEST_PHOTOZOOM = 3;
	private String mFileName = "";
	private String mImagePath;
	private File mFileZoomDir;

	private UserModel mUserModel;
	private XListView f0_profile_listview;
	private ImageView top_view_back;

	// private TextView get_nickname;
	private TextView get_gender;
//	private TextView mRefresh;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.f0_profile_list);
		mUserId = getIntent().getIntExtra(USER_ID, 0);
		Log.i("用户id", mUserId + "");
		initView();

		mUserModel = new UserModel(this);
		mUserModel.addResponseListener(this);

		if (mUserId != SESSION.getInstance().uid) {
			change_nickname.setClickable(false);
			// change_avartar.setClickable(false);
			change_gender.setClickable(false);
			change_mobile.setClickable(false);
			change_sinagture.setClickable(false);
			change_brief.setClickable(false);
		} else {
			mUserBalance.get();
		}
		EventBus.getDefault().register(this);
	}

	private void initView() {
		// 姓名和性别
		// get_nickname = (TextView) findViewById(R.id.tv_get_nickname);

		f0_profile_listview = (XListView) findViewById(R.id.f0_profile_listview);
		top_view_back = (ImageView) findViewById(R.id.top_view_back);
		TextView top_view_title = (TextView) findViewById(R.id.top_view_title);
		top_view_title.setText(getString(R.string.personal_profile));

//		mRefresh = (TextView) findViewById(R.id.top_view_right_text);
//		mRefresh.setBackgroundResource(R.drawable.refresh);
//		mRefresh.setVisibility(View.VISIBLE);
//		mRefresh.setText("");
		View view = View.inflate(F0_ProfileActivity.this,
				R.layout.f0_profile_header, null);
		f0_profile_listview.addHeaderView(view);
		f0_profile_listview.setPullLoadEnable(false);
		f0_profile_listview.loadMoreHide();
		f0_profile_listview.setRefreshTime();
		f0_profile_listview.setXListViewListener(this, 1);
		f0_profile_listview.setAdapter(null);

		change_nickname = (RelativeLayout) view
				.findViewById(R.id.change_nickname);
		// change_avartar = (RelativeLayout) view
		// .findViewById(R.id.change_avartar);
		change_gender = (RelativeLayout) view.findViewById(R.id.change_gender);
		change_mobile = (RelativeLayout) view.findViewById(R.id.change_mobile);
		change_sinagture = (RelativeLayout) view
				.findViewById(R.id.change_sinagture);
		get_gender = (TextView) view.findViewById(R.id.tv_get_gender);
		change_brief = (RelativeLayout) view.findViewById(R.id.change_brief);

		change_nickname.setOnClickListener(this);
		// change_avartar.setOnClickListener(this);
		change_gender.setOnClickListener(this);
		change_mobile.setOnClickListener(this);
		change_sinagture.setOnClickListener(this);
		change_brief.setOnClickListener(this);

		// mBack = (ImageView) findViewById(R.id.top_back_home);
		mAvatar = (RoundedWebImageView) findViewById(R.id.iv_avarta);

		mName = (TextView) findViewById(R.id.tv_name);
		mBalance = (TextView) findViewById(R.id.tv_balance);
		mSignature = (TextView) findViewById(R.id.tv_signature);

		mRefresh = (ImageView) findViewById(R.id.refresh);
		mUserBalance = new UserBalanceModel(this);
		mUserBalance.addResponseListener(this);
		mUserBalance.getProfile(mUserId);
		top_view_back.setOnClickListener(this);
		mAvatar.setOnClickListener(this);
		mRefresh.setOnClickListener(this);

	}

	@Override
	protected void onResume() {
		if (mUserId == SESSION.getInstance().uid) {
			mUserBalance.get();
			mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
			String userStr = mShared.getString("user", "");
			try {
				if (userStr != null) {
					JSONObject userJson = new JSONObject(userStr);
					mUser = new USER();
					mUser.fromJson(userJson);
					mImageLoader.displayImage(mUser.avatar.thumb, mAvatar,
							O2OMobile.options_head);
					if (!mUser.nickname.equals("") && mUser.nickname != null) {
						mName.setText(mUser.nickname);
					}
					if ((mUser.gender == 0 || mUser.gender == 1)
							&& String.valueOf(mUser.gender) != null) {

						if (mUser.gender == 0) {
							get_gender.setText("男");
							// Log.i("性别", "男");
						} else if (mUser.gender == 1) {
							get_gender.setText("女");
							// Log.i("性别", "女");
						} else {
							// Log.i("性别", "未知");
							get_gender.setText("未知");
						}

					}
					if (mUser.signature.equals("")) {
						mSignature.setText("没有签名");
					} else {
						mSignature.setText(mUser.signature);
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		super.onResume();
	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		if (url.endsWith(ApiInterface.USER_BALANCE)) {
			mBalance.setVisibility(View.VISIBLE);
			mBalance.setText("我的余额："
					+ Utils.formatBalance(mUserBalance.publicBalance)
					+ getString(R.string.yuan));
		} else if (url.endsWith(ApiInterface.USER_CHANGE_AVATAR)) {
			ToastView toast = new ToastView(this,
					getString(R.string.change_avatar_success));
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		} else if (url.endsWith(ApiInterface.USER_PROFILE)) {
			userprofileResponse response = new userprofileResponse();
			response.fromJson(jo);
			mUser = response.user;
			mImageLoader.displayImage(mUser.avatar.thumb, mAvatar,
					O2OMobile.options_head);
			if (!mUser.nickname.equals("") && mUser.nickname != null) {
				mName.setText(mUser.nickname);
				// get_nickname.setText(mUser.nickname);
			}
			if (mUser.gender == 0 || mUser.gender == 1) {

				if (mUser.gender == 0) {
					get_gender.setText("男");
					// Log.i("性别", "男");
				} else if (mUser.gender == 1) {
					get_gender.setText("女");
					// Log.i("性别", "女");
				} else {
					// Log.i("性别", "未知");
					get_gender.setText("未知");
				}

			}
			if (mUser.signature.equals("")) {
				mSignature.setText("没有签名");
			} else {
				mSignature.setText(mUser.signature);
			}
			// if (mUser.id == SESSION.getInstance().uid) {
			// if (mUser.user_group == ENUM_USER_GROUP.FREEMAN.value()) {
			// mUserBalance.getServiceList(mUser.id);
			// }
			// }
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CAMERA) {
			File files = new File(mFileName);
			if (files.exists()) {
				mImagePath = mFileName;
				mImagePath = startPhotoZoom(Uri.fromFile(new File(mImagePath)));
			}
		} else if (requestCode == REQUEST_PHOTO) {
			Uri selectedImage = data.getData();
			mImagePath = startPhotoZoom(selectedImage);
		} else if (requestCode == REQUEST_PHOTOZOOM) {
			File f = new File(mImagePath);
			if (f.exists()) {
				File file = new File(ImageUtil.zoomImage(mImagePath, 350));
				mUserBalance.changeAvatar(file);
				mUserBalance.getProfile(mUserId);
			} else {
				ToastView toast = new ToastView(this,
						getString(R.string.photo_not_exsit));
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
		}
	}

	private String startPhotoZoom(Uri uri) {

		if (mFileZoomDir == null) {
			mFileZoomDir = new File(O2OMobileAppConst.FILEPATH + "img/");
			if (!mFileZoomDir.exists()) {
				mFileZoomDir.mkdirs();
			}
		}

		String fileName;
		fileName = "/temp.jpg";

		String filePath = mFileZoomDir + fileName;
		File loadingFile = new File(filePath);

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 400);
		intent.putExtra("aspectY", 400);
		intent.putExtra("output", Uri.fromFile(loadingFile));// 输出到文件
		intent.putExtra("outputFormat", "PNG");// 返回格式
		intent.putExtra("noFaceDetection", true); // 去除面部检测
		intent.putExtra("return-data", false); // 不要通过Intent传递截获的图片
		startActivityForResult(intent, REQUEST_PHOTOZOOM);

		return filePath;

	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		// 修改手机号
		case R.id.change_mobile:
			intent = new Intent(F0_ProfileActivity.this,
					C5_EditMobileActivity.class);
			intent.putExtra("userId", mUserId);
			startActivity(intent);
			break;
		// 点击返回
		case R.id.top_view_back:
			finish();
			break;
		case R.id.change_sinagture: {
			intent = new Intent(F0_ProfileActivity.this,
					C12_EditSignatureActivity.class);
			intent.putExtra("userId", mUserId);
			startActivity(intent);
			break;

		}
		// case R.id.change_avartar: {
		// LayoutInflater inflater = LayoutInflater.from(this);
		// View view = inflater.inflate(R.layout.photo_dialog, null);
		// mDialog = new Dialog(this, R.style.dialog);
		// mDialog.setContentView(view);
		//
		// mDialog.setCanceledOnTouchOutside(true);
		// mDialog.show();
		// LinearLayout requsetCameraLayout = (LinearLayout) view
		// .findViewById(R.id.register_camera);
		// LinearLayout requestPhotoLayout = (LinearLayout) view
		// .findViewById(R.id.register_photo);
		// // 调用系统拍照
		// requsetCameraLayout.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// // TODO Auto-generate
		// mDialog.dismiss();
		// if (mFileDir == null) {
		// mFileDir = new File(O2OMobileAppConst.FILEPATH + "img/");
		// if (!mFileDir.exists()) {
		// mFileDir.mkdirs();
		// }
		// }
		// mFileName = O2OMobileAppConst.FILEPATH + "img/"
		// + "temp.jpg";
		// mFile = new File(mFileName);
		// Uri imageuri = Uri.fromFile(mFile);
		// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
		// intent.putExtra("return-data", false);
		// startActivityForResult(intent, REQUEST_CAMERA);
		// }
		// });
		//
		// requestPhotoLayout.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// // TODO Auto-generated method stub
		// mDialog.dismiss();
		// Intent picture = new Intent(Intent.ACTION_PICK,
		// MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		// startActivityForResult(picture, REQUEST_PHOTO);
		// }
		// });
		// break;
		//
		// }
		case R.id.change_gender: {
			showSelectGenderDialog();
			break;

		}
		case R.id.change_brief: {
			intent = new Intent(F0_ProfileActivity.this,
					C4_EditIntroActivity.class);
			intent.putExtra("userId", mUserId);
			startActivity(intent);
			break;

		}
		case R.id.change_nickname: {
			intent = new Intent(F0_ProfileActivity.this,
					C3_EditNameActivity.class);
			startActivity(intent);
			break;

		}
		case R.id.refresh: {
			if (mUserId == SESSION.getInstance().uid) {
				mUserBalance.get();
			}
			mUserBalance.getProfile(mUserId);
			break;

		}
		}
	}

	private void showSelectGenderDialog() {
		View view = View.inflate(this, R.layout.gender_view, null);
		mDialog = new Dialog(this, R.style.dialog);
		mDialog.setContentView(view);

		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();

		final TextView gender_men = (TextView) view
				.findViewById(R.id.gender_men);
		TextView gender_women = (TextView) view.findViewById(R.id.gender_women);

		gender_men.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mDialog.dismiss();
				// 设置性别为男
				mUserModel.changeGender(ENUM_USER_GENDER.MAN);
				mUserBalance.getProfile(mUserId);
			}
		});
		gender_women.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mDialog.dismiss();
				// 设置性别为女
				mUserModel.changeGender(ENUM_USER_GENDER.WOMAN);
				mUserBalance.getProfile(mUserId);
			}
		});
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	public void onEvent(Object event) {
		SharedPreferences shared = getSharedPreferences(
				O2OMobileAppConst.USERINFO, 0);
		Message message = (Message) event;
		if (message.what == MessageConstant.LOGINOUT) {
			finish();
		}

		if (message.what == MessageConstant.Change_Seivice) {
			mUserBalance.getServiceList(mUser.id);
		}

	}

	@Override
	public void onRefresh(int id) {
		// TODO Auto-generated method stub
		if (mUserId == SESSION.getInstance().uid) {
			mUserBalance.get();
		}
		mUserBalance.getProfile(mUserId);
	}

	@Override
	public void onLoadMore(int id) {
		// TODO Auto-generated method stub

	}
}
